import React, { Component } from 'react'
import {
    StyleSheet,
    View,
    Text,
    Image,
    ScrollView,
    TouchableOpacity,
    TouchableWithoutFeedback,
    RefreshControl,
    Platform,
    BackHandler
} from 'react-native';

const Dimensions = require('Dimensions');
const { width } = Dimensions.get('window');
// common 
import NavigatorBar from '../../common/NavigationBar';
// slider 
import Slider from './comps/Slider';
// Tab切换组件
import Lessons from '../../component/Lessons';
import RecommendTea from '../../component/RecommendTea';
import Mechanism from '../../component/Mechanism';
import Loading from '../../common/Loading'
// api 接口
import { listRecommendCourse, listRecommendTeachers, listRecommendOrgs, listBanner } from '../../api/home'
// 字体大小设置
import { px2dp } from '../../utils/px2dp';
import { setSpText, setHW } from '../../component/ScreenUtil'
import BaseBridge from '../../common/Native/BaseBridge';
var that
// 缓存数据
var cacheData = {
    'Lessons': {
        data: [],
        nextPage: 1,
        total: 0
    },
    'Teacher': {
        data: [],
        nextPage: 1,
        total: 0
    },
    'Mechanism': {
        data: [],
        nextPage: 1,
        total: 0
    }
}
var that;
export default class HomeIndex extends Component {
    constructor(props) {
        super(props);
        this.state = {
            LessonsList: [], // 推荐课程数据
            TeacherList: [],
            MechanismList: [],
            ListBanners: [],
            MiddleBanner: [],
            tabName: 'Lessons',
            firstTabSwitch: true,
            ready: true, // 加载完毕
            isRefreshing: false,
            isLoading: false,
            LessonsMore: false,
            TeacherMore: false
        };
        that=this;
    }
    componentDidMount() {
        // 获取课程数据
        cacheData = {
            'Lessons': {
                data: [],
                nextPage: 1,
                total: 0
            },
            'Teacher': {
                data: [],
                nextPage: 1,
                total: 0
            },
            'Mechanism': {
                data: [],
                nextPage: 1,
                total: 0
            }
        };
        this._fetchData();
        this._getAdvBanner();

        BackHandler.addEventListener('hardwareBackPress', that.handleBack);
        this.props.navigation.pressBack = that.handleBack;
    }
    /**
     * 获取广告
     */
    _getAdvBanner() {
        listBanner({}).then(res => {
            global.log(res, '------res slider');
            this.setState({
                ListBanners: res.TOPBANNERLIST,
                MiddleBanner: res.MIDDLEBANNERLIST
            })
        });
    }
    // 加载首页数据
    _fetchData(flag) {
        var json = {
            sendData: {},
            page: cacheData[this.state.tabName].nextPage,
            rows: 10
        }

        this.setState({
            isLoading: true
        })
        // 获取课程
        // global.log(this.hasMoreLessons(),'this.hasMoreLessons()')
        if (this.state.tabName == 'Lessons') {
            listRecommendCourse(json).then((res) => {
                cacheData[this.state.tabName].data = this.state.LessonsList.concat(res.LIST);
                cacheData[this.state.tabName].total = res.PAGINATION.TOTAL;
                var LessonsData = [...cacheData[this.state.tabName].data]
                global.log(cacheData, 'cacheData cacheData cacheData')
                
                setTimeout(()=>{
                    this.setState({
                        LessonsList: LessonsData,
                        isLoading: false,
                    })
                }, 300)
                if(flag) {
                    this.setState({
                        isRefreshing: false
                    })
                }
            });
        }
        else if (this.state.tabName == 'Teacher') {
            listRecommendTeachers(json).then((res) => {
                cacheData[this.state.tabName].data = this.state.TeacherList.concat(res.LIST);
                cacheData[this.state.tabName].total = res.PAGINATION.TOTAL;
                var TeacherData = [...cacheData[this.state.tabName].data];
                
                setTimeout(() => {
                    this.setState({
                        TeacherList: TeacherData,
                        isLoading: false
                    })
                }, 300)
                if (flag) {
                    this.setState({
                        isRefreshing: false
                    })
                }
            });
        }
        else {
            var MechanismData = {
                sendData: {
                    "P_ID": "004d1bf1-2f44-4077-a0e0-29653ce425f8",
                    "F_PROVINCE_ID": "158e657f-f386-4635-b6b2-a0080b2b6a60"
                },
                page: cacheData['Mechanism'].nextPage,
                rows: 10
            }
            listRecommendOrgs(MechanismData).then((res) => {
                cacheData[this.state.tabName].data = res.LIST;
                this.setState({
                    MechanismList: cacheData[this.state.tabName].data,
                    isLoading: false
                });
                if (flag) {
                    this.setState({
                        isRefreshing: false
                    })
                }
            });
        }

    }
    handleBack(e) {
        BaseBridge.backToExue();
    }
    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', that.handleBack)
    }
    removeHardBackPress() {
        BackHandler.removeEventListener('hardwareBackPress', that.handleBack)
    }
    // tab 切换事件
    tabHandle(item) {
        cacheData = {
            'Lessons': {
                data: [],
                nextPage: 1,
                total: 0
            },
            'Teacher': {
                data: [],
                nextPage: 1,
                total: 0
            },
            'Mechanism': {
                data: [],
                nextPage: 1,
                total: 0
            }
        }
        this.setState({
            tabName: item,
            LessonsList: [], // 推荐课程数据
            TeacherList: [],
            MechanismList: []
        }, () => {
            this._fetchData();
        });
    }
    // 刷新首页
    _onRefresh() {
        // console.log('on_refresh')
        cacheData = {
            'Lessons': {
                data: [],
                nextPage: 1,
                total: 0
            },
            'Teacher': {
                data: [],
                nextPage: 1,
                total: 0
            },
            'Mechanism': {
                data: [],
                nextPage: 1,
                total: 0
            }
        }
        this.setState({
            LessonsList: [], // 推荐课程数据
            TeacherList: [],
            MechanismList: [],
            isLoading: false,
            LessonsMore: true,
            TeacherMore: true,
            MechanismMore: false,
            isRefreshing: true
        });
        this._fetchData(true);
        this._getAdvBanner(true);
    }
    hasMoreTeacher() {
        if (this.state.TeacherList.length >= cacheData[this.state.tabName].total && cacheData[this.state.tabName].total > 0) {
            this.setState({
                TeacherMore: false
            });
            return false
        }
        return true
    }
    hasMoreLessons() {
        if (this.state.LessonsList.length >= cacheData[this.state.tabName].total && cacheData[this.state.tabName].total > 0) {
            this.setState({
                LessonsMore: false
            })
            return false
        }
        return true
    }
    hasMoreMechanism() {
        if (this.state.MechanismList.length >= cacheData[this.state.tabName].total && cacheData[this.state.tabName].total > 0) {
            this.setState({
                MechanismMore: false
            })
            return false
        }
        return true
    }
    // 加载更多数据
    _onScroll(event) {
        if (this.state.isLoading || (this.state.tabName == "Lessons" && !this.hasMoreLessons() || (this.state.tabName == "Teacher" && !this.hasMoreTeacher()) || (this.state.tabName == 'Mechanism' && !this.hasMoreMechanism()))) {
            return;
        }
        let y = event.nativeEvent.contentOffset.y;
        let height = event.nativeEvent.layoutMeasurement.height;
        let contentHeight = event.nativeEvent.contentSize.height;
        // 如果拖拽值超过底部50，且当前的scrollview高度大于屏幕高度，则加载更多
        const _num = contentHeight - height - y;
        if (Platform.OS == 'android' && (y + height >= contentHeight - 30)) {
            this.loadMoreData();
        }
        // ios 实现方式
        else if (contentHeight > height && _num < -20) {
            this.loadMoreData()
        }
    }
    // 加载更多数据
    loadMoreData() {
        this.setState({
            loadMore: true,
            isLoading: true
        }, () => {
            cacheData[this.state.tabName].nextPage = cacheData[this.state.tabName].nextPage + 1;
            this._fetchData()
        });
    }
    render() {
        return (
            <View style={styles.appContainer}>
                <NavigatorBar
                    title={'e课'}
                    style={styles.navigatorBar}
                    leftButton={this.renderLeftButton(require('../../assets/imgs/back.png'))}
                    rightButton={this.renderRightButton(require('../../assets/imgs/search.png'))}
                />
                {/* tree  */}
                {/* tree end */}
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh.bind(this)}
                            tintColor="#FF8A00"
                            title="加载中..."
                            titleColor="#ddd"
                            colors={['#FF8A00']}
                            progressBackgroundColor="#ffffff"
                            onResponderMove={(e) => this._onResponderMove(e)}
                        />
                    }
                    onScroll={this._onScroll.bind(this)}
                    scrollEventThrottle={40}
                    showsVerticalScrollIndicator={false}>
                    {/* header */}
                    {/* slider 轮播图 */}
                    <Slider listBanners={this.state.ListBanners} {...this.props} />
                    {/* slider end */}
                    <View style={styles.navWrapper}>
                        <TouchableOpacity style={styles.navItem} onPress={() => this.searchLessons()}>
                            <Image style={styles.navImage} source={require('../../assets/imgs/search_lesson.png')} />
                            <Text style={styles.navItemText}>找课程</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.navItem} onPress={() => this.searchTeachers()}>
                            <Image style={styles.navImage} source={require('../../assets/imgs/search_teacher.png')} />
                            <Text style={styles.navItemText}>找教师</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.navItem} onPress={() => this.searchMechanism()}>
                            <Image style={styles.navImage} source={require('../../assets/imgs/search_mechanism.png')} />
                            <Text style={styles.navItemText}>找机构</Text>
                        </TouchableOpacity>
                    </View>
                    {/* 广告位 */}
                    <TouchableWithoutFeedback onPress={() => this.goToAdv()}>
                        <View style={styles.advWrapper}>
                            {this.state.MiddleBanner.length > 0 ? <Image style={styles.advImage} source={{ uri: this.state.MiddleBanner && this.state.MiddleBanner[0].PIC }} /> : null}
                        </View>
                    </TouchableWithoutFeedback>
                    {/* tab切换 */}
                    <View>
                        <View style={styles.tabWrapper}>
                            <View style={styles.tabContainerWrapper}>
                                <TouchableOpacity style={[styles.tabNavItem, this.state.tabName == 'Lessons' && styles.tabActive]} onPress={() => this.tabHandle('Lessons')} >
                                    <Text style={[styles.tabNavItemText, this.state.tabName == 'Lessons' && styles.textActive]}>推荐课程</Text>
                                    <View style={[styles.line, this.state.tabName == 'Lessons' && styles.lineActive]}></View>
                                </TouchableOpacity>
                            </View>
                            <View style={styles.tabContainerWrapper}>
                                <TouchableOpacity style={[styles.tabNavItem, this.state.tabName == 'Teacher' && styles.tabActive]} onPress={() => this.tabHandle('Teacher')}>
                                    <Text style={[styles.tabNavItemText, this.state.tabName == 'Teacher' && styles.textActive]}>推荐老师</Text>
                                    <View style={[styles.line, this.state.tabName == 'Teacher' && styles.lineActive]}></View>
                                </TouchableOpacity>
                            </View>
                            <View style={styles.tabContainerWrapper}>
                                <TouchableOpacity style={[styles.tabNavItem, this.state.tabName == 'Mechanism' && styles.tabActive]} onPress={() => this.tabHandle('Mechanism')}>
                                    <Text style={[styles.tabNavItemText, this.state.tabName == 'Mechanism' && styles.textActive]}>推荐机构</Text>
                                    <View style={[styles.line, this.state.tabName == 'Mechanism' && styles.lineActive]}></View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                    <View style={styles.tabContentWrapper}>
                        {this.state.tabName == 'Lessons' ? <View tabName="Lessons" tabLabel="推荐课程" 
                        style={[styles.tabContent, styles.tabTeacherContent]}>
                            <Lessons ref='Lessons' LessonsList={this.state.LessonsList} {...this.props} />
                        </View> : null}
                        {this.state.tabName == 'Teacher' ? <View tabName="RecommendTea" tabLabel="推荐老师" style={styles.tabContent}>
                            <RecommendTea ref='RecommendTea' TeacherList={this.state.TeacherList} from={'HomeIndex'} reSearchData={() => this._onRefresh()} {...this.props} />
                        </View> : null}
                        {this.state.tabName == 'Mechanism' ? <View tabName="Mechanism" tabLabel="推荐机构" style={[styles.tabContent, styles.mechanismTabContent]}>
                            <Mechanism ref='Mechanism' MechanismList={this.state.MechanismList}  {...this.props} />
                        </View> : null}
                        {this.state.loading ? <Loading /> : null}
                    </View>
                    {/* 解决遮住底部栏的高度 */}
                    {/* loadingMoreStatus */}
                    {((this.state.tabName == 'Lessons' || this.state.tabName == 'Teacher')) && <View>
                        {
                            this.state.tabName == 'Lessons'
                                ? (<View style={styles.loadMore}>
                                    {this.state.isLoading ? <Text style={styles.loadMoreText}>正在加载中...</Text> : <Text style={styles.loadMoreText}>{this.state.LessonsList.length == 0 ? '暂无推荐课程' : (this.state.LessonsList.length == cacheData[this.state.tabName].total ? '已经全部加载完毕' : '')}</Text>}
                                </View>) : (<View style={styles.loadMore}>
                                    {this.state.isLoading ? <Text style={styles.loadMoreText}>正在加载中...</Text> : <Text style={styles.loadMoreText}>{this.state.TeacherList.length == 0 ? '暂无推荐老师' : (this.state.TeacherList.length == cacheData[this.state.tabName].total ? '已经全部加载完毕' : '')}</Text>}
                                </View>)
                        }
                    </View>}
                    {/* loadingMoreStatus end */}
                    {/* <BottomBarLimit /> */}
                </ScrollView>
            </View>
        )
    }
    _onResponderMove(e) {
        // console.log(e, 'eeeeeeeeeeeeeeeee')
    }
    goToAdv() {
        if (!this.state.MiddleBanner.length) return;
        if (this.state.MiddleBanner[0].URL) {
            this.props.navigation.navigate('AdvView', {
                advURL: this.state.MiddleBanner[0].URL
            })
        }
        else if (this.state.MiddleBanner[0].HTML) {
            this.props.navigation.navigate('AdvView', {
                htmlStr: this.state.MiddleBanner[0].HTML
            })
        }
        this.removeHardBackPress()
    }
    goBack() {
        BaseBridge.backToExue();
    }
    // 渲染按钮
    renderLeftButton(image) {
        var that = this;
        return <TouchableOpacity
            style={[global.CommonStyleSheet.NavLeftButton]}
            onPress={() => {
                that.goBack();
            }}>
            <Image
                style={{ width: 34, height: 34 }}
                source={image} />
        </TouchableOpacity>;
    }
    renderRightButton(image) {
        return <TouchableOpacity
            onPress={() => this.goToSearchPage()}
            style={{
                padding: 8, flexDirection
                    : 'row', justifyContent: 'center', alignItems: 'center',
            }}
        >
            <Image
                style={{ width: 14, height: 14, marginRight: 1 }}
                source={image} />
            <Text style={{ marginLeft: 2, color: '#666' }}>搜索</Text>
        </TouchableOpacity>;
    }
    // 调转到搜索课程
    searchLessons() {
        this.props.navigation.navigate('LessonSearchPage');
        this.removeHardBackPress()
    }
    // 跳转到搜索老师
    searchTeachers() {
        this.props.navigation.navigate('TeacherSearchPage');
        this.removeHardBackPress()
    }
    searchMechanism() {
        this.props.navigation.navigate('MechanismSearchPage');
        this.removeHardBackPress()
    }
    // 跳转到搜索页面
    goToSearchPage() {
        this.props.navigation.navigate('SearchPage');
        this.removeHardBackPress()
    }
}
const tabPadding = 18;
const styles = StyleSheet.create({
    appContainer: {
        backgroundColor: "#F7F7F9",
        flex: 1
    },
    tabContentWrapper: {
        backgroundColor: "#fff",
    },
    tabbarContainer: {
        marginTop: setHW(20),
        height: setHW(80),
        borderWidth: 0.5,
        borderTopWidth: 0,
        borderLeftWidth: 0,
        borderRightWidth: 0,
        backgroundColor: 'white',
        justifyContent: 'space-between'
    },
    tab: {
        width: setHW(240),
        height: setHW(80),
        alignItems: 'center',
        justifyContent: 'center',
        paddingLeft: tabPadding,
        paddingRight: tabPadding,
    },
    headerContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: setHW(88),
        paddingLeft: setHW(20),
        paddingRight: setHW(20)
    },
    navigatorBar: {
        backgroundColor: '#fff'
    },
    // 导航
    navWrapper: {
        flexDirection: 'row',
        paddingTop: setHW(40),
        paddingLeft: setHW(40),
        paddingRight: setHW(40),
        paddingBottom: setHW(40),
        backgroundColor: 'white'
    },
    navItem: {
        flex: 1,
        alignItems: 'center',
    },
    navImage: {
        width: setHW(100),
        height: setHW(100),
        marginBottom: setHW(20)
    },
    navItemText: {
        fontSize: px2dp(30)
    },
    // 广告位
    advWrapper: {
        marginTop: setHW(20),
        height: setHW(166),
        alignItems: 'center',
        backgroundColor: "#fff"
    },
    advImage: {
        width: width,
        height: setHW(166),
        resizeMode: 'cover'
    },
    tabWrapper: {
        flexDirection: 'row',
        marginTop: setHW(20),
        paddingLeft:setHW(60),
        paddingRight:setHW(60),
        backgroundColor:'#fff',
        height:setHW(88),
        borderBottomWidth: 1,
        borderBottomColor: '#EBEBEB',
        // backgroundColor: 'red'
        
    },
    tabContainerWrapper: {
        flex:1,
        height:setHW(88),
    },
    tabNavItem: {
        flex:1,
        height:setHW(88),
        flexDirection:'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    tabNavItemText: {
        color: '#333',
        paddingTop: setHW(6),
        fontSize: setSpText(30)
    },
    textActive: {
        color: '#FF9920',
        fontWeight: 'bold'
    },
    line: {
        width: setHW(48),
        height: setHW(6),
        position: 'absolute',
        backgroundColor: '#fff',
        bottom:setHW(8),
        borderRadius:setHW(6)
    },
    lineActive: {
        borderColor: '#FF8A00',
        backgroundColor: '#FF8A00',
    },
    tabContent: {
        flex: 1,
        overflow: 'hidden',
    },
    mechanismTabContent: {
        height: setHW(600)
    },
    tabTeacherContent: {
        paddingRight: setHW(30),
        paddingLeft:  setHW(30),
    },
    commandLessons: {
        marginTop:  setHW(20),
        flexDirection: 'row',
    },
    tabContainer: {
        flex: 1,
        height:  setHW(88),
        borderBottomColor: '#eeeeee',
        borderBottomWidth: 1,
        borderTopColor: '#eeeeee',
        borderTopWidth: 1,
        backgroundColor: '#FAFAFA',
    },
    contentStyle: {
        flex: 1,
        flexDirection: 'row',
    },
    itemTab: {
        justifyContent: 'center',
        height:  setHW(88),
        paddingLeft:  setHW(12),
        paddingRight:  setHW(12),
        borderBottomWidth:  setHW(6),
        borderBottomColor: '#FAFAFA'
    },
    //选中状态
    itemActiveTab: {
        borderBottomWidth:  setHW(6),
        borderBottomColor: '#2766cf'
    },
    itemText: {
        color: '#757575',
        fontSize: setSpText(28),
    },
    itemActiveText: {
        color: '#2766cf',
        fontSize: setSpText(28),
        fontWeight: '700'
    },
    tabBtn: {
        width:  setHW(80),
        height:  setHW(88),
        backgroundColor: '#FAFAFA',
        borderLeftWidth: 1,
        borderLeftColor: '#eeeeee',
        borderBottomColor: '#eeeeee',
        borderBottomWidth: 1,
        borderTopColor: '#eeeeee',
        borderTopWidth: 1,
        justifyContent: 'center', alignItems: 'center',
    },
    tabBtnIcon: {
        width: setHW(32),
        height: setHW(32)
    },
    // loadMore
    loadMore: {
        flexDirection: 'row',
        justifyContent: 'center',
        height: setHW(100),
        alignItems: 'center',
    },
    loadMoreText: {
        color: '#ddd'
    }
});